import '@umijs/max';
import React, { useEffect, useRef, useState } from 'react';
import { chartRetryUsingPost, listMyChartVoByPageUsingPost } from '@/services/api/chartController';
import {
  Avatar,
  BackTop,
  Button,
  Card,
  Divider,
  Form,
  Input,
  message,
  Modal,
  Popover,
  Result,
  Space,
  Switch,
  Tabs,
} from 'antd';
import { List } from 'antd/lib';
import { history, useModel } from '@@/exports';
import EChartsReact from 'echarts-for-react';
import Search from 'antd/es/input/Search';
import ChartErrorBoundary from '@/pages/Bi/Components/ChartErrorBoundary';
import {
  CopyOutlined,
  PlusCircleOutlined,
  TeamOutlined,
  UserOutlined,
  UsergroupAddOutlined,
} from '@ant-design/icons';
import {
  addBiTeamUsingPost,
  joinBiTeamUsingPost,
  shareBiTeamUsingGet,
} from '@/services/api/biTeamController';

/**
 * 我的图表页面
 *
 * @constructor
 */
const MyChartPage: React.FC = () => {
  const initSearchParams = {
    current: 1,
    pageSize: 4,
  };
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};

  const [chartList, setChartList] = useState<API.ChartVO[]>();
  const [total, setTotal] = useState<number>();
  const [loading, setLoading] = useState<boolean>(false);
  const [autoRefresh, setAutoRefresh] = useState<boolean>(false);
  const [activeKey, setActiveKey] = useState<string>('individual');
  const [joinTeamModal, setJoinTeamModal] = useState<boolean>(false);
  const [joinTeamForm] = useState<API.BiJoinTeamRequest>({});
  const joinTeamFormRef = useRef(null);

  const chartRefs = useRef<{ [key: string]: EChartsReact | null }>({});

  const [showDownloadButtons, setShowDownloadButtons] = useState<{ [key: string]: boolean }>({});

  const chartSourceMenu = [
    {
      key: 'individual',
      label: '个人',
      children: null,
      icon: <UserOutlined />,
    },
    {
      key: 'team',
      label: '团队',
      children: null,
      icon: <TeamOutlined />,
    },
  ];

  const loadData = async () => {
    try {
      setLoading(true);

      const res = await listMyChartVoByPageUsingPost({ ...searchParams, chartSource: activeKey });
      if (res.data) {
        // 渲染数据预处理
        res.data.records?.forEach((data) => {
          // 状态为成功
          if (data.status === 2) {
            try {
              const chartOption = JSON.parse(data.genChart ?? '{}');
              // chartOption.title = undefined;
              data.genChart = chartOption;
            } catch (e) {
              return;
            }
          }
        });

        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取我的图表失败');
      }
    } catch (e: any) {
      message.error('获取我的图表失败 ' + e.message);
    }
    setLoading(false);
  };

  const chartType = {
    line: '折线图',
    bar: '柱状图',
    pie: '饼图',
    radar: '雷达图',
    scatter: '散点图',
    histogram: '直方图',
    box: '箱线图',
    area: '面积图',
    bubble: '气泡图',
    heatmap: '热力图',
  } as any;

  const getChartType = (value: string) => {
    return chartType[value] ?? '未定义';
  };

  // 自动刷新
  let interval: string | number | NodeJS.Timeout | undefined = undefined;
  useEffect(() => {
    if (autoRefresh) {
      interval = setInterval(() => {
        loadData();
      }, 2000);
    } else {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [autoRefresh]);

  /**
   *重新生成图表
   */
  const chartRetryHandle = async (id: any) => {
    if (!id) return;
    try {
      const res = await chartRetryUsingPost({ id });
      if (res.data) {
        loadData();
        message.success('正在重新分析数据 请等待. . .');
      } else {
        message.error('重试失败');
      }
    } catch (e) {}
  };

  /**
   * 跳转到图表数据详情页面
   * @param id
   */
  const openDetailHandle = (id: any) => {
    if (id === null) return;
    history.push(`/bi/chart-data-detail/${id}`);
  };

  /**
   * 创建团队协作
   */
  const createTeamHandle = async (chartId: any) => {
    setLoading(true);
    try {
      const res = await addBiTeamUsingPost({ chartId });
      if (res.data) {
        message.success('创建团队成功');
      } else {
        message.error('团队创建失败');
      }
    } catch (e) {
    } finally {
      setLoading(false);
    }
  };

  /**
   * 分享团队
   */
  const shareTeamHandle = async (chartId: any) => {
    setLoading(true);
    try {
      const res = await shareBiTeamUsingGet({ chartId });
      if (res.data) {
        let shareData = '团队ID：' + res.data.id + '\n密码：' + res.data.joinPassword;
        await navigator.clipboard.writeText(shareData);
        message.success('分享链接已复制到剪切板！！');
      } else {
        message.error('分享失败，网络不佳，请稍后再试');
      }
    } catch (e) {
    } finally {
      setLoading(false);
    }
  };

  /**
   * 加入团队事件
   */
  const joinTeamHandle = async () => {
    try {
      setLoading(true);
      if (joinTeamForm.teamId) {
        const res = await joinBiTeamUsingPost(joinTeamForm);
        if (res.data) {
          message.success('成功加入团队');
          loadData();
          setJoinTeamModal(false);
          //@ts-ignore
          joinTeamFormRef.current.resetFields();
        } else {
          message.error('加入团队失败，请稍后再试');
        }
      }
    } catch (e) {
    } finally {
      setLoading(false);
    }
  };

  const downloadChart = (data: API.ChartVO) => {
    const chartRef = chartRefs.current[data.id];
    if (chartRef) {
      const echartsInstance = chartRef.getEchartsInstance();
      const imageUrl = echartsInstance.getDataURL({
        type: 'png', // 图片格式，支持 png、jpeg
        pixelRatio: 2, // 图片分辨率，2 表示高清
        backgroundColor: '#fff', // 背景颜色
      });

      // 创建一个 <a> 标签并触发下载
      const link = document.createElement('a');
      link.href = imageUrl;
      link.download = `chart_${data.name}.png`; // 下载的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  const genResultCopy = async (genResult: string) => {
    try {
      await navigator.clipboard.writeText(genResult);
      message.success('复制成功');
    } catch (err) {
      message.error('复制失败');
    }
  };

  /**
   * 搜索参数
   */
  useEffect(() => {
    loadData();
  }, [searchParams, activeKey]);

  return (
    <div className="my-chart-page">
      <BackTop />
      <Card style={{ marginBottom: 16 }}>
        <Tabs
          defaultActiveKey={activeKey}
          items={chartSourceMenu}
          onChange={(activeKey) => {
            setActiveKey(activeKey);
            setSearchParams({
              ...initSearchParams,
            });
          }}
        />
        <div style={{ marginRight: 3 }} />
        <div>
          <Search
            placeholder="请输入图表名称"
            enterButton="搜索"
            size="large"
            loading={loading}
            onSearch={(value) => {
              setSearchParams({
                ...initSearchParams,
                name: value,
              });
            }}
          />
          <Divider />
          <Space>
            <div>
              自动刷新：
              <Switch
                checkedChildren="开"
                unCheckedChildren="关"
                defaultChecked={autoRefresh}
                onChange={(checked) => {
                  setAutoRefresh(checked);
                }}
              />
            </div>
            <Button
              onClick={() => {
                loadData();
              }}
            >
              刷新
            </Button>
            <div style={{ marginRight: 3 }} />
            <Button icon={<PlusCircleOutlined />} onClick={() => setJoinTeamModal(true)}>
              加入团队
            </Button>
          </Space>
        </div>
      </Card>
      <List
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({ ...searchParams, current: page, pageSize });
          },
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total: total,
        }}
        loading={loading}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card style={{ width: '100%', minHeight: 720 }}>
              <List.Item.Meta
                avatar={<Avatar src={currentUser?.userAvatar} />}
                title={currentUser?.userName}
                description={
                  <Space>
                    {'图表类型：' +
                      getChartType(item.chartType ?? '') +
                      ' | 最后更新时间：' +
                      item.updateTime}

                    {activeKey === 'individual' && (
                      <Button
                        danger
                        shape="round"
                        icon={<UsergroupAddOutlined />}
                        onClick={() => createTeamHandle(item.id)}
                      >
                        创建团队
                      </Button>
                    )}
                    {activeKey === 'team' && (
                      <Button
                        danger
                        shape="round"
                        icon={<UsergroupAddOutlined />}
                        onClick={() => shareTeamHandle(item.id)}
                      >
                        分享链接
                      </Button>
                    )}
                  </Space>
                }
              />
              <Divider />
              <Space
                split={<Divider style={{ borderColor: '#1177dc', width: 5 }} type="vertical" />}
              >
                <div>
                  {'图表名称：' + item.name}
                  <div style={{ marginBottom: 16 }} />
                  {'分析目标：' + item.goal}
                </div>
                <>
                  {item.status === 2 && (
                    <Button onClick={() => openDetailHandle(item.id)}>详情</Button>
                  )}
                  {(item.status === 3 || item.status === 4) && (
                    <Button danger onClick={() => chartRetryHandle(item.id)}>
                      重试
                    </Button>
                  )}
                </>
              </Space>
              <Divider />
              <>
                {item.status === 0 && (
                  <>
                    <Result
                      status="warning"
                      title="待生成"
                      subTitle={item.execMessage ?? '当前图表队列繁忙，请耐心等候'}
                    />
                  </>
                )}
                {item.status === 1 && (
                  <>
                    <Result status="info" title="图表生成中" subTitle={item.execMessage} />
                  </>
                )}
                {item.status === 2 && (
                  <>
                    <div
                      style={{ position: 'relative' }}
                      onMouseEnter={() =>
                        setShowDownloadButtons({ ...showDownloadButtons, [item.id]: true })
                      }
                      onMouseLeave={() =>
                        setShowDownloadButtons({ ...showDownloadButtons, [item.id]: false })
                      }
                    >
                      <ChartErrorBoundary>
                        <EChartsReact
                          ref={(e) => {
                            if (e) {
                              chartRefs.current[item.id] = e;
                            }
                          }}
                          option={item.genChart}
                        />
                      </ChartErrorBoundary>
                      {showDownloadButtons[item.id] && (
                        <Button
                          style={{
                            position: 'absolute',
                            top: 10,
                            right: 10,
                            zIndex: 1000,
                            backgroundColor: 'rgba(255, 255, 255, 0.8)',
                          }}
                          onClick={() => downloadChart(item)}
                        >
                          下载图表
                        </Button>
                      )}
                    </div>
                    <Divider>结论</Divider>
                    <Popover
                      content={
                        <Button
                          type="primary"
                          icon={<CopyOutlined />}
                          onClick={() => genResultCopy(item.genResult as string)}
                        >
                          复制
                        </Button>
                      }
                      trigger="hover"
                    >
                      <div style={{ display: 'inline-block', cursor: 'pointer' }}>
                        {item.genResult}
                      </div>
                    </Popover>
                  </>
                )}
                {(item.status === 3 || item.status === 4) && (
                  <>
                    <Result status="error" title="图表生成失败" subTitle={item.execMessage} />
                  </>
                )}
              </>
            </Card>
          </List.Item>
        )}
      />
      <Modal
        title="加入团队"
        open={joinTeamModal}
        onOk={() => {
          joinTeamHandle();
        }}
        onCancel={() => {
          setJoinTeamModal(false);
        }}
      >
        <Form
          name="basic"
          labelCol={{ span: 4, offset: 1 }} // 调整标签的布局
          wrapperCol={{ span: 16, offset: 1 }} // 调整输入框的布局
          style={{ maxWidth: 600 }}
          onFinish={joinTeamHandle}
          autoComplete="off"
          ref={joinTeamFormRef}
        >
          <Form.Item
            label="团队ID"
            name="teamId"
            rules={[{ required: true, message: '必须输入团队ID!' }]}
          >
            <Input onChange={(e) => (joinTeamForm.teamId = e.target.value as any)} />
          </Form.Item>

          <Form.Item label="密码" name="joinTeamPassword">
            <Input.Password onChange={(e) => (joinTeamForm.joinPassword = e.target.value)} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default MyChartPage;
